/**  
 * All rights Reserved, Designed By www.beonelot.com
 * @Package: com.jinxin.platform.eleinspect.controller
 * @Filename: EleinspectRecordController.java
 * @Description: TODO(EleinspectRecordController)
 * @author: 金鑫智慧
 * @date: 2020-03-30
 * @version: V1.0
 * @Copyright: 2020 www.beonelot.com Inc. All rights reserved.
 * 注意：本内容仅限于重庆金鑫智慧科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.jinxin.platform.cdelecinspect.controller;


import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.InvokeCfg;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.base.common.support.BusinessDelegate;
import com.jinxin.platform.cdelecinspect.domain.SysUserVO;
import com.jinxin.platform.cdelecinspect.mapper.EleinspectAttachmentMapper;
import com.jinxin.platform.cdelecinspect.mapper.pojo.*;
import com.jinxin.platform.cdelecinspect.result.ResultTool;
import com.jinxin.platform.cdelecinspect.rpc.SysUserRpc;
import com.jinxin.platform.cdelecinspect.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * TODO(EleinspectRecordController)
 * @Classn: EleinspectRecordController
 * @author Lynn
 * @date 2020-03-30
 */
@Slf4j
@RestController
@RequestMapping("/insLineRecord")
public class EleinspectRecordController {
    @Autowired
    private EleinspectRecordService recordService;
    @Autowired
    private EleinspectItemsRecordService eleinspectItemsRecordService;
    @Autowired
    private BusinessDelegate businessDelegate;
    @Autowired
    private EleinspectTaskService eleinspectTaskService;
    @Autowired
    EleinspectPointManageService eleinspectPointManageService;
    @Autowired
    private EleinspectMappingPointItemsService mappingPointItemsService;
    @Autowired
    private SysUserRpc sysUserRpc;
    @Autowired
    private EleinspectAttachmentMapper attachmentMapper;

    @RequestMapping("/listPointItemsForApp")
    public Map<String,Object> listPointItemsForApp(String lineId,String taskId){
        if(StringUtils.isEmpty(lineId) || StringUtils.isEmpty(taskId)){
            log.info("listPointItemsForApp: lineId or taskId is null");
            return null;
        }
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null){
            log.info("获取当前用户失败: ");
            return null;
        }
        Map<String,Object> resultMap = new HashMap<>();
        HashMap<String,Object> param = new HashMap<>();
        // 存放点位和项目的map,key是点位的id
        HashMap<String,Object> pointItemMap = new HashMap<>();
        param.put("param",lineId);
        List<EleinspectPointManage> list = eleinspectPointManageService.listPointsByLineId(lineId);
        List<EleinspectPointManage> list2 = new ArrayList<>();
        for(EleinspectPointManage pointRecord : list){
            String pointId = pointRecord.getPointId();
            HashMap<String,Object> param2 = new HashMap<>();
            param2.put("pointId", pointId);
            List<EleinspectMappingPointItems> pointItems = mappingPointItemsService.listPointItems(param2);
            HashMap<String,Object> param3 = new HashMap<>();
            param3.put("recordLineId",lineId);
            param3.put("recordPointId",pointId);
            param3.put("recordTaskId",taskId);
            param3.put("recordInspectId",currentUser.getUserId());
            EleinspectRecord record = recordService.getOne(param3);
            String pId = record != null ? record.getRecordId() : "";
            Integer isClockedIn = record != null && !StringUtils.isEmpty(record.getRecordClockinTime()) ? 1 :2;
            List<EleinspectMappingPointItems> pointItems2 = new ArrayList<>();
            if(!StringUtils.isEmpty(pId)){
                for (EleinspectMappingPointItems pointItem : pointItems) {
                    HashMap<String,Object> param4 = new HashMap<>();
                    param4.put("itemPointRecordId",pId);
                    param4.put("itemRecordItemId",pointItem.getItemId());
                    EleinspectItemRecord itemRecord = eleinspectItemsRecordService.selectOne(param4);
                    if(itemRecord != null){
                        pointItem.setMappingResult(itemRecord.getItemRecordStatus());
                        pointItem.setRecordDealwith(itemRecord.getRecordDealwith());
                        pointItem.setMappingProblemDetail(itemRecord.getItemRecordDescription());
                        HashMap<String,Object> param5 = new HashMap<>();
                        param5.put("mainId",itemRecord.getItemRecordId());
                        List<EleinspectAttachment> attachList = attachmentMapper.list(param5);
                        StringBuilder sb = new StringBuilder();
                        for(EleinspectAttachment attachment : attachList){
                            sb.append(attachment.getPath()).append(",");
                        }
                        if(!StringUtils.isEmpty(sb.toString())){
                            pointItem.setAttachments(sb.substring(0,sb.lastIndexOf(",")));
                        }
                    }
                    pointItems2.add(pointItem);
                }
            }
            pointRecord.setIsClockedIn(isClockedIn);
            list2.add(pointRecord);
            pointItemMap.put(pointId, pointItems2);
//            recordService.getOne();
        }
        resultMap.put("pointList",list2);
        resultMap.put("pointItemMap", pointItemMap);
        resultMap.put("code",0);
        resultMap.put("msg","");
        return resultMap;
    }

    @RequestMapping("/listByCondition")
    public Map<String,Object> listByCondition(String lineName, String inspectResult, String startTime,
                                              String endTime, String inspectPerson, String ifMiss,
                                              @RequestParam long page, @RequestParam long limit,boolean isFromApp){
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code",0);
        resultMap.put("msg","");
        HashMap<String,Object> param = new HashMap<>();
        param.put("lineName", lineName);
        param.put("inspectResult", inspectResult);
        param.put("inspectPerson", inspectPerson);
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        param.put("ifMiss", ifMiss);
        param.put("page", page);
        param.put("limit", limit);
        if(isFromApp){
            param.put("history", "history");
            SysUserVO currentUser = sysUserRpc.getCurrentUser();
            if(currentUser != null){
                param.put("staffId", currentUser.getUserId());
            }else {
                resultMap.put("count",0);
                resultMap.put("data",null);
                return resultMap;
            }
        }
        resultMap.put("count",recordService.listLineRecordsCount(param));
        resultMap.put("data",recordService.listLineRecords(param));
        return resultMap;
    }

    @RequestMapping("/listPointResults")
    public Map<String,Object> listPointResults(String recordId){
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code",0);
        resultMap.put("msg","");
        resultMap.put("data",recordService.listPointResultsById(recordId));
        return resultMap;
    }

    //app接口-更新项目记录
    @RequestMapping("/updateItemRecord")
    public JsonResult updateItemRecord(String itemRecordId) {
        //通过项目记录id获取项目记录
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey("app");
        cfg.setClassName("ItemRecordRpcService");
        cfg.setFunName("getItemRecord");
        HashMap<String, String> map = new HashMap<>();
        map.put("itemRecordId", itemRecordId);
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        if(result.getSuccess()){
            JSONObject jsonObject = JSONObject.parseObject(result.getData().toString());
            String recordTime = String.valueOf(jsonObject.get("itemRecordTime"));
            int itemRecordStatus = Integer.parseInt(String.valueOf(jsonObject.get("itemRecordStatus")));
            String itemRecordDescription = String.valueOf(jsonObject.get("itemRecordDescription"));
            String itemRecordAttachId = String.valueOf(jsonObject.get("itemRecordAttachId"));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date itemRecordTime = null;
            try {
                itemRecordTime = simpleDateFormat.parse(recordTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //更新项目记录
            EleinspectItemRecord eleinspectItemRecord = eleinspectItemsRecordService.selectByKey(itemRecordId);
            eleinspectItemRecord.setItemRecordTime(itemRecordTime);
            eleinspectItemRecord.setItemRecordStatus(itemRecordStatus);
            eleinspectItemRecord.setItemRecordDescription(itemRecordDescription);
            eleinspectItemRecord.setItemRecordAttachid(itemRecordAttachId);
            eleinspectItemsRecordService.updateByKey(eleinspectItemRecord);

            //更新点位记录
            EleinspectRecord eleinspectRecord = recordService.selectByKey(eleinspectItemRecord.getItemPointRecordId());
            if (itemRecordStatus == 1 && eleinspectRecord.getRecordPointStatus() == 0){
                //点位状态 0正常 1异常
                eleinspectRecord.setRecordPointStatus(1);
            }
            recordService.updateByKey(eleinspectRecord);
            log.info(result.toString());
        }
        return result;
    }

    //app接口-点位打卡
//    @RequestMapping("/inspectPoint")
//    public JsonResult doTask(String recordId) {
//        InvokeCfg cfg = new InvokeCfg();
//        cfg.setModuleKey("app");
//        cfg.setClassName("EleinspectPointRpcService");
//        cfg.setFunName("inspectPoint");
//        HashMap<String, String> map = new HashMap<>();
//        map.put("recordId", recordId);
//        cfg.setArgs(map);
//        JsonResult result = businessDelegate.invoke(cfg);
//        if(result.getSuccess()){
//            JSONObject jsonObject = JSONObject.parseObject(result.getData().toString());
//            String QRCodePointId = String.valueOf(jsonObject.get("QRCodePointId"));
//            EleinspectRecord eleinspectRecord = recordService.selectByKey(QRCodePointId);
//            //巡检打卡时间
//            if (eleinspectRecord.getRecordInspectTime() != null){
//                eleinspectRecord.setRecordInspectTime(new Date());
//            }
//            //没有漏巡
//            eleinspectRecord.setRecordMissedInspect(0);
//            recordService.updateByKey(eleinspectRecord);
//
//            //任务完成时间
//            HashMap param = new HashMap();
//            param.put("recordLineId",eleinspectRecord.getRecordLineId());
//            List<EleinspectRecord> list = recordService.list(param);
//            if (list.size() > 0){
//                int index = 0; //点位打卡计数
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                try {
//                    Date latestTime = df.parse("0000-00-00 00:00:00");
//                    for (EleinspectRecord eleinspectRecord1 : list){
//                        if (eleinspectRecord1.getRecordInspectTime() != null){
//                            if (eleinspectRecord1.getRecordInspectTime().after(latestTime)){
//                                latestTime = eleinspectRecord1.getRecordInspectTime();
//                            }
//                            index++;
//                        }
//                    }
//                    //线路上所有点位打卡成功
//                    if (index == list.size()){
//                        EleinspectTask eleinspectTask = eleinspectTaskService.selectByKey(eleinspectRecord.getRecordTaskId());
//                        //判断任务完成状态：0未开始 1进行中 2提早完成 3超时完成 4按时完成 5已取消
//                        if(latestTime.after(eleinspectTask.getEarliestFinishTime()) && latestTime.before(eleinspectTask.getLatestFinishTime())){
//                            eleinspectTask.setStatus(4);
//                        }else if (latestTime.before(eleinspectTask.getEarliestFinishTime())){
//                            eleinspectTask.setStatus(2);
//                        }else if(latestTime.after(eleinspectTask.getLatestFinishTime())){
//                            eleinspectTask.setStatus(3);
//                        }
//                        eleinspectTask.setFinishTime(df.format(latestTime));
//                        eleinspectTaskService.updateByKey(eleinspectTask);
//                    }
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//
//            }
//            log.info(result.toString());
//        }
//        return result;
//    }



}
